package com.iyjhsoc.game.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iyjhsoc.game.annotation.OrderBy;
import com.iyjhsoc.game.annotation.QueryParams;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class QueryUtil {

    public static QueryWrapper createQueryWrapper(Object o){
        if(o == null){
            return new QueryWrapper();
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        Class aClass = o.getClass();
        try {
            Constructor c = aClass.getDeclaredConstructor();
            c.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Field[] fields = aClass.getDeclaredFields();
        for(Field field:fields){
            QueryParams declaredAnnotation = field.getDeclaredAnnotation(QueryParams.class);
            OrderBy orderBy = field.getDeclaredAnnotation(OrderBy.class);
            if(declaredAnnotation != null){
                Object invoke = null;
                String name = field.getName();
                try {
                    Method method = aClass.getMethod("get" + capitalize(name));
                    invoke = method.invoke(o);
                    if(invoke == null){
                        continue;
                    }
                } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                    continue;
                }
                queryWrapper.eq(generateDownLine(name),invoke);
            }
            if(orderBy != null){
                queryWrapper.orderByAsc(generateDownLine(field.getName()));
            }
        }
        return queryWrapper;
    }

    public static String generateDownLine(String name){
        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0;i<name.length();i++){
            char c = name.charAt(i);
            if( c > 'A' && c < 'Z'){
                stringBuffer.append("_");
                stringBuffer.append((char) (c+32));
            } else{
                stringBuffer.append(c);
            }
        }
        return stringBuffer.toString();
    }

    public static String capitalize(String inputString) {

        // get the first character of the inputString
        char firstLetter = inputString.charAt(0);

        // convert it to an UpperCase letter
        char capitalFirstLetter = Character.toUpperCase(firstLetter);

        // return the output string by updating
        //the first char of the input string
        return inputString.replace(inputString.charAt(0), capitalFirstLetter);
    }


}
